package com._520it.crm.service.impl;

import com._520it.crm.domain.CommodityType;
import com._520it.crm.mapper.CommodityTypeMapper;
import com._520it.crm.page.PageResult;
import com._520it.crm.query.CommodityTypeQueryObject;
import com._520it.crm.service.ICommodityTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 王梦参 on 2017/10/9.
 */
@Service
public class CommodityTypeService implements ICommodityTypeService {
    @Autowired
    private CommodityTypeMapper commodityTypeMapper;
    private List<Long> ids = new ArrayList<>();
    @Override
    public int deleteByPrimaryKey(Long id) {
        List<CommodityType> commodityType = commodityTypeMapper.selectByParentId(id);
        getIds(commodityType);
        ids.add(id);
        for (Long delid : ids) {
            commodityTypeMapper.deleteByPrimaryKey(delid);
        }
        return 0;
    }

    @Override
    public int insert(CommodityType record) {
        return commodityTypeMapper.insert(record);
    }

    @Override
    public CommodityType selectByPrimaryKey(Long id) {
        return commodityTypeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<CommodityType> selectAll() {
        return commodityTypeMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(CommodityType record) {
        return commodityTypeMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<CommodityType> listAllType() {
        return commodityTypeMapper.listAllType();
    }

    @Override
    public PageResult query(CommodityTypeQueryObject qo) {
        Integer totalCount = commodityTypeMapper.queryTotalCount(qo);
        List data = new ArrayList<>();
        if(qo.getTypeId()>0){
            data.add(selectByPrimaryKey(qo.getTypeId()));
        }
        if(totalCount == null || totalCount<=0){
            return new  PageResult(1,data);
        }
        List<CommodityType> result = commodityTypeMapper.queryData(qo);
        if(qo.getTypeId()>0){
            result.add(selectByPrimaryKey(qo.getTypeId()));
            totalCount = totalCount+1;
        }
        return new PageResult(totalCount,result);
    }

    @Override
    public void updateStrat(CommodityType type) {
        if(type.getStrat()==1){
            type.setStrat(CommodityType.NORMAL);
        }else{
            type.setStrat(CommodityType.LEAVE);
        }
        commodityTypeMapper.updateStrat(type);
    }

    public void getIds(List<CommodityType> commodityType) {
        if(commodityType == null || commodityType.size()==0){
            return ;
        }
        for (CommodityType type : commodityType) {
            ids.add(type.getId());
            getIds(type.getChildren());
        }
    }
}
